#include "ViewerMainWindow.h"
#include "ui_ViewerMainWindow.h"
#include "NetworkThread.h"
#include "MeshObject.h" 
#include "Plane.h"
#include "Box.h"
#include "stdio.h"
#include "ElementData.h"
#include "Logger.h"

ViewerMainWindow::ViewerMainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ViewerMainWindow)
{
    ui->setupUi(this);

    // Viewer
    float m[16] = {1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0};
    unsigned char c[3] = {220, 220, 220};

    viewer = new Viewer(this);
    ui->viewerLayout->addWidget(viewer);
    char *name = new char[10];
                strcpy(name, "xr1_weel");
                Element *mesh = new MeshObject(name, c, m);
    plane = new Plane(100, c, m);
    viewer->addStaticElement(mesh);
    viewer->addStaticElement(plane);

    ui->disconnectButton->setEnabled(false);

    connect(ui->fpsSpinBox, SIGNAL(valueChanged(int)), this, SLOT(changeFPS(int)));
    connect(ui->connectButton, SIGNAL(clicked()), this, SLOT(connectButtonClicked()));
    connect(ui->disconnectButton, SIGNAL(clicked()), this, SLOT(disconnectButtonClicked()));
}

ViewerMainWindow::~ViewerMainWindow()
{
    delete ui;
}

void ViewerMainWindow::changeFPS(int fps)
{
    viewer->stopAnimation();
    viewer->setAnimationPeriod(1000 / fps);
    viewer->startAnimation();
}

void ViewerMainWindow::connectButtonClicked()
{
    ui->connectButton->setEnabled(false);
    ui->disconnectButton->setEnabled(true);

    serverThread = new NetworkThread(ui->IPEdit->text());
    connect(serverThread, SIGNAL(changeElementSign(float*)), this, SLOT(changeElements(float*)));
    connect(serverThread, SIGNAL(addElementSign(ElementData*)), this, SLOT(addElement(ElementData*)));
    connect(serverThread, SIGNAL(networkErrorSign(QString)), this, SLOT(networkError(QString)));

    serverThread->start();
}

void ViewerMainWindow::disconnectButtonClicked()
{
    serverThread->terminate();
    ui->connectButton->setEnabled(true);
    ui->disconnectButton->setEnabled(false);
    viewer->clearElements();
}

void ViewerMainWindow::changeElements(float *m)
{
    viewer->UpdateObjects(m);
}

void ViewerMainWindow::networkError(QString s)
{
    ui->connectButton->setEnabled(true); 
    QMessageBox::critical(0, "Viewer", s);
}

void ViewerMainWindow::addElement(ElementData *ed)
{
    unsigned char *c;

    c = ed->getColor();

    viewer->addElement(ed->getElementType(), ed->getTransformationMatrix(), c, ed->getData());
}
